package com.shu.security;

import java.util.Collection;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.shu.entity.SysUser;
import com.shu.service.SysUserRoleService;
import com.shu.service.SysUserService;


/**
 * 从数据库中读入用户的密码，角色信息，是否锁定，账号是否过期等
 * 
 */
@Component
public class MyUserDetailService implements UserDetailsService {
    private static final Log logger = LogFactory.getLog(MyUserDetailService.class);

	@Resource
    private SysUserService userService;
	@Resource
    private SysUserRoleService userRoleService;
    
    /**
     * 数据库交互获取用户拥有的权限角色，并设置权限
     */
    @Override
    public UserDetails loadUserByUsername(String userCode) throws UsernameNotFoundException, DataAccessException {
        // 根据登录用户名获取用户信息
        SysUser user = userService.getUser(userCode);
        if(null == user) {
        	logger.info("不存在用户："+userCode);
        	throw new UsernameNotFoundException(userCode);
        }
        // 存放权限
        Collection<GrantedAuthority> auths = userRoleService.getRoleByUserName(userCode);
        //实现UserDetails接口的User对象
        user.setAuthorities(auths);
        logger.info("载入用户："+userCode);
        return new User(user.getUsername(),user.getPassword(),true,true,true,true,user.getAuthorities());
    }
    
    
}
